<template>
    <div class="container">
        <div class="login-container">
            <el-form ref='formRef' :model="form" :rules="rules" size="large" label-position="top">
                <div class="title-container">
                    <h2 class="title">用户登录</h2>
                </div>
                <el-form-item label="用户名" prop="name">
                    <el-input v-model="form.name" />
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="form.password" type="password" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" size="large" @click="onSubmit('formRef')">登录</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script>
import { ElMessage } from 'element-plus'

export default {
    name: "LoginView",
    components: {
    },

    data() {
        return {
            form: {
                name: '',
                password: ''
            },
            rules: {
                name: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' }
                ],

            }
        }
    },

    methods: {
        onSubmit: function (formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.$http.post("/admin/auth/login", {
                        username: this.form.name,
                        password: this.form.password
                    }).then((res) => {
                        localStorage.setItem('token', res.data.token)
                        this.$router.push({ path: '/record' })
                        ElMessage({
                            message: '登录成功',
                            type: 'success',
                            plain: true,
                            duration: 1000
                        })
                    }).catch(() => {

                    })
                } else {
                    return false
                }
            })

        }
    },
}
</script>

<style scoped>
.container {
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
}

.login-container {
    padding: 30px;
    background-color: #7f7f86;
    width: 500px;
    height: 340px;
}

.title-container {
    display: flex;
    justify-content: center;
    align-items: center;
}

.el-form-item button {
    width: 100%;
    /* 设置按钮的宽度为 100% */
}
</style>